package alarm

import (
	"bytes"
	"encoding/json"
	"fmt"
	"go.uber.org/zap"
	"io/ioutil"
	"net/http"
	"service_keepalive/logger"
)

var sendApi = "https://oapi.dingtalk.com/robot/send"

type DingTalkAlarm struct {
	AccessToken string
	Profile     string
}
type SendMsg struct {
	Text    SendText `json:"text"`
	Msgtype string   `json:"msgtype"`
}
type SendText struct {
	Content string `json:"content"`
}

func (d *DingTalkAlarm) Alarm(serverName string, address string, status string) {
	url := fmt.Sprintf("%s?access_token=%s", sendApi, d.AccessToken)
	m := SendMsg{
		Text: SendText{
			Content: "服务提醒: \n" +
				"环境: " + d.Profile + "\n" +
				"服务名: " + serverName + "\n" +
				"服务地址: " + address + "\n" +
				"状态: " + status,
		},
		Msgtype: "text",
	}
	bs, _ := json.Marshal(m)
	r := bytes.NewReader(bs)
	resp, _ := http.Post(url, "application/json", r)
	respBody, _ := ioutil.ReadAll(resp.Body)
	logger.Info("钉钉提醒，返回结果", zap.String("result", string(respBody)))
}
